/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.taglib.core.grid;

import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
 * <p>Body of this tag will be rendered if and only if filter by field
 * specified in enclosing filter tag has been enabled.
 * <br />
 * This tag is only valid when nested within some filter tag
 * </p>
 * <p><a href="FilterEnabledTag.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.9 $ $Date: 2006/08/03 10:08:19 $
 * @jsp.tag name="filterEnabled"
 * body-content="scriptless"
 * @see com.blandware.atleap.webapp.taglib.core.grid.NumberFilterTag
 * @see com.blandware.atleap.webapp.taglib.core.grid.DateFilterTag
 * @see com.blandware.atleap.webapp.taglib.core.grid.StringFilterTag
 * @see com.blandware.atleap.webapp.taglib.core.grid.SetFilterTag
 */
public class FilterEnabledTag extends SimpleTagSupport {

    /**
     * Processes the tag
     *
     * @throws JspException
     * @throws IOException
     */
	public void doTag() throws JspException, IOException {

		PageContext pageContext = (PageContext) getJspContext();

		// This tag is only valid when nested within any 'filter' tag, so check this

		BaseFilterTag parentFilterTag = (BaseFilterTag) findAncestorWithClass(this, BaseFilterTag.class);
		if ( parentFilterTag == null ) {
			JspTagException e = new JspTagException("Parent tag is invalid! This tag is only valid when nested within 'filter' tag");
			throw e;
		}

		// Render body if enclosing filter is enabled

		String fieldName = parentFilterTag.getFieldName();

		GridTag parentGridTag = (GridTag) findAncestorWithClass(this, GridTag.class);
		Grid grid = parentGridTag.getGrid();

		if ( grid.isFilterEnabled(fieldName) ) {
			JspFragment body = getJspBody();
			if ( body != null ) {
				body.invoke(null);
			}
		}
	}

}
